import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import { io, Socket } from 'socket.io-client';
import { getToken } from '@/utils/local';
import { baseURL } from '@/utils/request';
import { Toast } from 'antd-mobile';

type MessageType = {
  msg: string;
  timestamp: number;
  type: string;
};
export default function Chat() {
  // 用于缓存 socket.io 客户端实例
  const clientRef = useRef<Socket | null>(null);
  const [intMsg, setIntMsg] = useState('');
  const [msgList, setmsgList] = useState<MessageType[]>([]);
  useEffect(() => {
    clientRef.current = io(baseURL, {
      query: {
        token: getToken(),
      },
      transports: ['websocket'],
    });
    clientRef.current.on('connect', () => {
      // 第一次连接成功后的回调
      console.log('第一次连接成功后的回调');
      console.log('document.body.scrollHeight', document.body.scrollHeight);
      setmsgList([{ type: 'robot', msg: '你好', timestamp: Date.now() }]);
    });
    // 监听收到消息的事件
    clientRef.current.on('message', (data: MessageType) => {
      console.log('>>>>收到 socket.io 消息:', data);
      setmsgList((msgList) => {
        return [...msgList, { ...data, type: 'robot' }];
      });
    });
    // 发送消息的事件
    return () => {
      clientRef.current?.close();
    };
  }, []);

  const handleSend = () => {
    if (intMsg.trim() === '') return Toast.show({ content: '请输入内容' });
    // 发送消息的事件
    clientRef.current?.emit('message', { msg: intMsg, timestamp: Date.now() });
    setmsgList((msgList) => {
      return [...msgList, { type: 'user', msg: intMsg, timestamp: Date.now() }];
    });
    setIntMsg('');
  };
  // 监听聊天数据的变化，改变聊天容器元素的 scrollTop 值让页面滚到最底部
  useEffect(() => {
    window.scrollTo({
      // 页面有多高，就滚动多少
      top: document.body.scrollHeight,
      // behavior: 'smooth', 平滑滚动
      behavior: 'smooth',
    });
  }, [msgList]);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed={true}>小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list">
        {/* 机器人的消息 */}
        {msgList.map((item) => {
          return item.type === 'robot' ? (
            <div className="chat-item" key={item.timestamp}>
              <Icon type="iconbtn_xiaozhitongxue" />
              <div className="message">{item.msg}</div>
            </div>
          ) : (
            <div className="chat-item user" key={item.timestamp}>
              <img
                src={'http://toutiao.itheima.net/images/user_head.jpg'}
                alt=""
              />
              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        {/* 底部消息输入框 */}
        <div className="input-footer">
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={intMsg}
            onChange={(e) => setIntMsg(e.target.value)}
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={handleSend}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
